<?php
/**
 * 图标管理
 * Created by gii.
 * User: Gii
 * Date: 2022/03/18
 * Time: 16:49
 */

namespace App\Http\Admin\Logics;

use App\Extend\Debug;
use App\Models\Models\System\SystemAccount;
use App\Models\Models\System\SystemAccountAuth;
use Illuminate\Support\Str;

class AccountLogic
{
	public static function getListWithCount($where=[], $field='*', $page=1, $limit=10, $order=['id', 'desc']) {
        $where = SystemAccount::getSelfWhereCommon($where);
		return SystemAccount::getListWithCountCommon($where, $field, $page, $limit, $order);
	}

	public static function getAll() {
		return SystemAccount::getAllCommon();
	}

	public static function del($id) {
        // 删除账号
		SystemAccount::delByPkCommon($id);

        // 删除权限
        SystemAccountAuth::delByPkCommon($id);
        return true;
	}

	public static function update($data) {
		return SystemAccount::updateCommon($data);
	}

	public static function add($data) {
		$accountId = SystemAccount::addCommon($data);
        if(!$accountId) {
            Debug::setDebug("账号保存失败");
            return false;
        }

        return SystemAccountAuth::addByAccount($accountId);
	}

	public static function getOne($id) {
		return SystemAccount::getLineByPkCommon($id);
	}

	public static function status($id, $status) {
		return SystemAccount::status($id, $status);
	}

    /**
     * 生成密码
     * @param $password
     * @return false|string|null
     */
    public static function makePassword($password='') {
        if(!$password) {
            $password = Str::random(6);
        }
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * 重置密码,返回值是新密码
     * @param $id
     * @return false|string
     */
    public static function resetPassword($id) {
        $password = Str::random(6);
        $data = [
            'id'        => $id,
            'password'  => self::makePassword($password),
        ];
        $res = SystemAccount::updateCommon($data);
        if(!$res) {
            Debug::setDebug('密码重置失败');
            return false;
        }
        return $password;
    }

    /**
     * 修改密码
     * @param $password
     * @return bool
     */
    public static function changePassword($passwordOldInput, $password) {
        $hash = LoginLogic::getPassword();
        if(!LoginLogic::checkPassword($passwordOldInput, $hash)) {
            Debug::setDebug('原密码不正确');
            return false;
        }

        $id = LoginLogic::getId();
        $data = [
            'id' => $id,
            'password' => self::makePassword($password),
        ];
        $res = SystemAccount::updateCommon($data);
        if(!$res) {
            Debug::setDebug('密码修改失败');
            return false;
        }
        return true;
    }
}
